﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JWTExtentions
{
    public static class CollectionExtensions
    {
        //注册jwt加密验证

        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
               .AddJwtBearer(options =>
               {

                   //取出私钥
                   var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
                   options.TokenValidationParameters = new TokenValidationParameters()
                   {
                       //验证发布者
                       ValidateIssuer = true,
                       ValidIssuer = builder.Configuration["Authentication:Issuer"],
                       //验证接收者
                       ValidateAudience = true,
                       ValidAudience = builder.Configuration["Authentication:Audience"],
                       //验证是否过期
                       ValidateLifetime = true,
                       //验证私钥
                       IssuerSigningKey = new SymmetricSecurityKey(secretByte),

                   };
               });
        }
    }
}
